<template>
    <div class="container">
        <div class="page-head">
            <div class="left">
                <el-form :inline="true" :model="query" @submit.native.prevent>
                    <el-form-item>
                        <el-button type="danger" @click="showCreateView"><i class="el-icon-plus"
                                style="margin-right: 5px"></i>添加</el-button>
                    </el-form-item>
                    <el-form-item>
                        <picker-view class="rem6" type="category" v-model="query.category_id" :multiple="true"
                            placeholder="信息类型" :filter="{ is_sale: 1, is_member_category: 1 }"></picker-view>
                    </el-form-item>
                    <el-form-item>
                        <picker-view class="rem6" type="visitStatus" v-model="query.status" :multiple="true"
                            placeholder="回访状态"></picker-view>
                    </el-form-item>
                    <!-- 是否逾期 overdue -->
                    <el-form-item>
                        <el-select class="rem6" v-model="query.overdue" placeholder="逾期状态" clearable>
                            <el-option label="未逾期" :value="0"></el-option>
                            <el-option label="已逾期" :value="1"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item>
                        <el-date-picker class="date-range" v-model="query.next_visit_time" type="daterange"
                            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                            value-format="yyyy-MM-dd">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-input v-model="query.keyword" placeholder="客户姓名 / 手机号" clearable></el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-input v-model="query.fullname" placeholder="客户姓名" clearable></el-input>
                    </el-form-item>
                    <el-button type="primary" native-type="submit" @click="doSearch">搜索</el-button>
                </el-form>
            </div>

            <!-- 更多搜索 -->
            <div class="right">
                <el-popover placement="bottom" width="500" trigger="click" popper-class="popover">
                    <el-form label-width="200px" label-position="right">
                        <template v-for="(item, key) in tableFields">
                            <el-form-item :key="key" :label="item.title">
                                <el-switch v-model="item.open" active-color="#13ce66" :active-value="1"
                                    :disabled="item.disabled" inactive-color="#ff4949" :inactive-value="0"
                                    @change="changeSwitch"></el-switch>
                            </el-form-item>
                        </template>
                    </el-form>

                    <el-button slot="reference" type="primary" style="margin-right: 8px"><i class="el-icon-setting"
                            style="margin-right: 5px"></i>设置</el-button>
                </el-popover>

                <el-popover placement="bottom" width="500" trigger="click">
                    <el-form :model="query" label-width="80px" label-position="right" @submit.native.prevent>
                        <el-form-item label="渠道">
                            <source-picker-view ref="sourcePickerRef" type="source" v-model="query.source_id"
                                placeholder="请选择渠道"></source-picker-view>
                        </el-form-item>
                        <el-form-item label="部门">
                            <dpt-picker-view ref="sourcePickerRef" type="department" v-model="query.department_id"
                                placeholder="请选择部门"></dpt-picker-view>
                        </el-form-item>
                        <el-form-item label="创建人">
                            <picker-view type="user" v-model="query.creator_id"></picker-view>
                        </el-form-item>
                        <el-form-item label="分配人">
                            <picker-view type="user" v-model="query.from_user_id"></picker-view>
                        </el-form-item>
                        <el-form-item label="分配状态">
                            <el-radio-group v-model="query.assign_status">
                                <el-radio label="0">未分配</el-radio>
                                <el-radio label="1">已分配</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="跟进人">
                            <picker-view type="user" v-model="query.user_id"></picker-view>
                        </el-form-item>
                        <el-form-item label="是否推荐">
                            <el-radio-group v-model="query.is_recommend">
                                <el-radio label="0">不推荐</el-radio>
                                <el-radio label="1">推荐</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="企业">
                            <el-input v-model="query.company_name" placeholder="企业"></el-input>
                        </el-form-item>
                        <el-form-item label="预产期">
                            <el-input v-model="query.event_date" placeholder="预产期"></el-input>
                        </el-form-item>
                        <el-form-item label="">
                            <el-input v-model="query.table_amount" placeholder=""></el-input>
                        </el-form-item>
                        <el-form-item label="无效原因">
                            <el-select v-model="query.cause" placeholder="请选择无效原因">
                                <el-option v-for="item in invalidList" :key="item.id" :label="item.title"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="回访时间">
                            <el-date-picker v-model="query.visit_date_range" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="分配时间">
                            <el-date-picker v-model="query.allocate_date_range" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="创建时间">
                            <el-date-picker v-model="query.create_date_range" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="warning" @click="doReset">重置</el-button>
                            <el-button type="primary" @click="doSearch">搜索</el-button>
                        </el-form-item>
                    </el-form>
                    <el-button slot="reference" type="primary"><i class="el-icon-search"
                            style="margin-right: 5px"></i>更多</el-button>
                </el-popover>
            </div>
        </div>

        <el-table ref="tableView" height="tableHeight" class="page-body" v-loading="loading" :data="tableData"
            :fit="true" border @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <template v-for="(item, key) in tableFields">
                <el-table-column v-if="item.open == 1 && item.action" :key="key" :label="item.title" :width="item.width"
                    :align="item.align ? item.align : 'center'" :prop="item.field" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-link type="primary" @click="funcProxy(item.action, scope.row)">{{ scope.row[item.field]
                        }}</el-link>
                    </template>
                </el-table-column>
                <el-table-column v-else-if="item.open" :key="key" :label="item.title" :width="item.width"
                    :align="item.align ? item.align : 'center'" :prop="item.field"
                    show-overflow-tooltip></el-table-column>
            </template>
        </el-table>

        <!-- 分页 -->
        <div class="page-foot">
            <div class="left">
                <el-button type="primary" icon="el-icon-share" v-has="'customer-share'" @click="showShareView">分配客资</el-button>
                <el-button type="primary" icon="el-icon-download" v-has="'customer-export'" @click="exportNext">导出预约客户</el-button>
            </div>
            <div class="right">
                <common-pagination :total="pg.total" :page.sync="pg.page" :limit.sync="pg.limit"
                    @getList="getTableData"></common-pagination>
            </div>
        </div>

        <!-- 添加客资 -->
        <create-view ref="createView" @getTableData="getTableData"></create-view>
        <!-- 客资详情 -->
        <detail-view ref="detailView" :parent="_self"></detail-view>
        <!-- 分配客资 -->
        <share-view ref="shareView" @submit="doShare"></share-view>
    </div>
</template>

<script>
import defaultFields from "@/config/allocate.js";

import {
    getAllocateListApi,
    allocateHandleApi,
    exportAllocateApi, doExportApi
} from "@/api/customer/member.js";

import pagination from "@/components/mixins/pagination.vue";
import sourcePickerView from "@/components/picker/source.vue";
import dptPickerView from "@/components/picker/department.vue";
import pickerView from "@/components/picker/select.vue";

import createView from "../create/create.vue";
import detailView from "./detail.vue";
import shareView from "@/components/picker/share.vue";

const query = {
    is_loading: 0,
    keyword: "",
    category_id: "",
    status: "",
    assign_status: "",
    source_id: "",
    creator_id: "",
    from_user_id: "",
    user_id: "",
    department_id: "",
    is_recommend: "",
    company_name: "",
    event_date: "",
    table_amount: "",
    cause: "",
    visit_date_range: [],
    allocate_date_range: [],
    create_date_range: [],
    next_visit_time: [],
    next: 1,
    overdue: "",
};
export default {
    namespaced: true,
    components: {
        createView,
        detailView,
        shareView,
        sourcePickerView,
        dptPickerView,
        pickerView,
    },
    provide() {
        return {
            pageIndex: this,
        };
    },
    mixins: [pagination],
    data() {
        return {
            query: JSON.parse(JSON.stringify(query)),
            loading: false,
            tableFields: [],
            tableData: [],
            dateTypeList: [{
                id: "create_time",
                title: "创建时间",
            },
            {
                id: "allocate_time",
                title: "分配时间",
            },
            {
                id: "visit_time",
                title: "跟进时间",
            },
            ],
            departmentTree: [],
        };
    },
    computed: {
        invalidList() {
            let localData = localStorage.getItem("invalidPickerList");
            if (localData) {
                return JSON.parse(localData);
            } else {
                return [];
            }
        },
    },
    created() {
        this.getTableFields();
        this.getTableData();
    },
    methods: {
        doSearch() {
            this.resetPg();
            this.getTableData();
        },
        getTableFields() {
            const allocateFields = localStorage.getItem("allocate-fields");
            if (allocateFields) {
                this.tableFields = JSON.parse(allocateFields);
            } else {
                localStorage.setItem("allocate-fields", JSON.stringify(defaultFields));
                return (this.tableFields = defaultFields);
            }
        },
        getTableData() {
            let params = Object.assign({}, this.query);
            params["pagination"] = this.pg;
            this.loading = true;
            getAllocateListApi(params).then((res) => {
                this.tableData = res.data.list;
                this.setPg(res);
                this.loading = false;
            });
        },
        exportNext() {
            let _this = this;
            // 检查 next_visit_time 是否为 null 或 undefined
            if (!_this.query.next_visit_time || _this.query.next_visit_time.length === 0) {
                this.$message.error('请选择日期时间');
                return false;
            } 
            const params = Object.assign({}, this.query)
            params['pagination'] = this.pg
            doExportApi(params).then((res) => {
                if (res.code == '200') {
                    let link = document.createElement('a');
                    link.href = res.data.url;

                    window.open(link.href, 'blank');
                    // link.click();

                } else {
                    // 提醒
                    this.$message.error(res.message)
                }
            })
        },
        doReset() {
            this.query = JSON.parse(JSON.stringify(query));
        },
        handleCascader(e) {
            let last = e.length - 1;
            this.query.department_id = e[last];
        },
        funcProxy(name, args) {
            if (this[name] && typeof this[name] === "function") {
                this[name](args);
            }
        },
        // 新建客资
        showCreateView() {
            this.$refs["createView"].showDrawer();
        },
        // 显示客资详情
        showDetail(row) {
            this.$refs["detailView"].showDrawer(row);
        },
        showShareView() {
            if (this.selectedRow.length == 0) {
                this.$message.error("请选择要分配的客资");
                return;
            }
            let ids = this.selectedRow.map((e) => e.id);
            this.$refs["shareView"].showDialog(ids);
        },
        doShare(userIds) {
            let options = {};
            let allocateIds = this.selectedRow.map((e) => e.id);
            options["allocateIds"] = allocateIds;
            options["ids"] = userIds;

            allocateHandleApi(options).then((res) => {
                if (res.code == 200) {
                    this.$message.success(res.msg);
                    this.clearSelection();
                } else {
                    this.$message.error(res.msg);
                }
            });
        },
        changeSwitch() {
            localStorage.setItem("allocate-fields", JSON.stringify(this.tableFields));
            this.$refs["tableView"].doLayout();
        },
    },
};
</script>

<style lang="scss">
.table-list {
    .customer-tag {
        margin-right: 5px;
    }
}

.popover {
    height: calc(100vh - 120px);
    overflow-y: scroll;
}

.bottom-box {
    display: flex;
    justify-content: center;
    align-items: center;

    .funcs-box {
        flex: 1;
        text-align: left;

        .func-item {
            margin-right: 8px;
        }
    }

    .pagination-box {
        flex: 1;
        text-align: right;
    }
}
</style>
